import { useState, useEffect, createElement } from 'react';
import { Modal, Button, Space, message } from 'antd';
import { DownOutlined } from '@ant-design/icons';
import { getMessage, TextWidget } from '@inbiz/react';
import { useApp } from '@inbiz/render';
import TreeAndTable from '@inbiz/basic/TreeAndTable';
import {
  useGetMessageGroupAllEffect,
  useGetMessageAllTreeGroupEffect,
} from './useMessageEffect';
import {
  SortableContainer,
  SortableElement,
  SortableHandle,
} from 'react-sortable-hoc';
import { InbizIcon, RenderModalToBody } from '@inbiz/utils';
import { move } from './utils';
import nowStyle from './index.less';

const transferData = (treeData: any) => {
  return treeData?.map((item: any) => {
    return {
      title: item.GroupName ?? item.DisplayName,
      key: item.GroupId ?? item.AppId,
      children: item.Trees
        ? item.Trees.length >= 1
          ? transferData(item.Trees)
          : []
        : [],
    };
  });
};


// 兼容导入站点消息
const getTableList = (data: any[], appId: string, set?: boolean) => {
  const newArr: any[] = []
  let tableKey = '';
  let key = '';
  let itemAppId = '';
  data.forEach((item: any) => {
    tableKey = item.TableKey ? item.TableKey : `${item.AppId}|${item.Key}`
    itemAppId = set ? item.AppId === appId ? '{AppId}' : item.AppId : tableKey.startsWith('{AppId}') ? appId : item.AppId.replaceAll('{AppId}', appId)
    key = set ? tableKey.replaceAll(appId + "|", '{AppId}|') : tableKey.replaceAll('{AppId}', appId)
    newArr.push({
      ...item,
      AppId: itemAppId,
      TableKey: key
    })
  })
  return newArr
}
const SelectMessageGroup = (props: any) => {
  const appInfo = useApp();
  const [visible, $visible] = useState(Boolean(props.hideSelectVisible));
  const [selectGroup, $selectGroup] = useState(getTableList([...props.value], appInfo.AppId) || []);
  const [sureGroup, $sureGroup] = useState(getTableList([...props.value], appInfo.AppId) || []);
  // 是否展开选中消息分组tag列表
  const [showTag, $showTag] = useState<boolean>(false);
  const appTree = useGetMessageAllTreeGroupEffect();
  const requestGroup = useGetMessageGroupAllEffect();

  const ok = () => {
    $visible(false);
    const newGroup = selectGroup;
    const newMap = new Map();
    newGroup.forEach((item: any) => {
      newMap.set(item.TableKey, item);
    });
    const transferGroup = [...newMap.values()];
    const tableList = getTableList(transferGroup, appInfo.AppId, true)
    $sureGroup(tableList);
    $selectGroup(tableList);
    props.onChange(tableList);
  };
  const close = () => {
    $selectGroup(sureGroup);
    $visible(false);
    props.onCancel?.()
  };

  useEffect(() => {
    $selectGroup(getTableList([...props.value], appInfo.AppId) || [])
    $sureGroup(getTableList([...props.value], appInfo.AppId) || [])
  }, [props.value, appInfo.AppId])

  if (!appTree) {
    return null;
  }

  const del = (id: string) => {
    const nowGroup = sureGroup.filter((item: any) => item.TableKey != id);
    $sureGroup(nowGroup);
    $selectGroup(nowGroup);
    props.onChange(nowGroup);
  };

  // 拖动排序
  const onSortEnd = async ({
    oldIndex,
    newIndex,
  }: {
    oldIndex: number;
    newIndex: number;
  }) => {
    try {
      if (oldIndex !== newIndex) {
        const arr = move(sureGroup, oldIndex, newIndex);
        $sureGroup(arr);
        props.onChange(arr);
      }
    } catch (err) {
      message.error(
        <TextWidget>SelectMessageGroup.message_sort_fial</TextWidget>,
      );
    }
  };

  // 弹窗footerDOM
  const RederFooter = () => {
    return (
      <div className={nowStyle['page-select-model-footer']}>
        <div className={nowStyle['select-count-nav']}>
          <p>
            <TextWidget>SelectMessageGroup.select_tatol</TextWidget>：
            <span>{selectGroup.length}</span>
            &nbsp;&nbsp;
            <DownOutlined
              onClick={() => $showTag(!showTag)}
              style={
                showTag
                  ? { transform: 'scaleY(.8) rotate(180deg)' }
                  : { transform: 'scaleY(.8) rotate(0)' }
              }
            />
          </p>
        </div>
        <Space>
          <Button key="cancel" onClick={close}>
            <TextWidget>global.cancel</TextWidget>
          </Button>
          <Button key="submit" type="primary" onClick={ok}>
            <TextWidget>global.sure</TextWidget>
          </Button>
        </Space>
      </div>
    );
  };


  const columnName: string = getMessage('SelectMessageGroup.column_group_name');
  const treeData = transferData(appTree);
  return (
    <>
      <div className={nowStyle.selectBox} style={{ display: props.hideSelectVisible ? 'none' : 'flex' }}>
        <Button
          type="primary"
          onClick={() => {
            $visible(!visible);
          }}
          style={{ marginRight: '110px' }}
        >
          <TextWidget>SelectMessageGroup.pick</TextWidget>
        </Button>
        {sureGroup.length > 0 && (
          <SortableList
            sureGroup={sureGroup}
            onSortEnd={onSortEnd}
            del={del}
            useDragHandle
          />
        )}
      </div>

      {visible && (
        <Modal
          forceRender
          title={<TextWidget>SelectMessageGroup.pick_model_title</TextWidget>}
          centered
          visible={true}
          width={800}
          bodyStyle={{ height: 488 }}
          onCancel={close}
          footer={[<RederFooter key="footer" />]}
        >
          <TreeAndTable
            treeData={treeData}
            inputPlaceholder={getMessage('SelectMessageGroup.placeholder')}
            onTreeSelect={async ({
              key,
              searchText,
              pageIndex,
              pageSize,
            }: {
              key: string;
              pageIndex: number;
              searchText: string;
              pageSize: number;
            }) => {
              const tableList = await requestGroup({
                appId: key,
                searchText: searchText ? searchText : '',
                pageIndex: pageIndex ? pageIndex : 1,
                pageSize: pageSize ? pageSize : 10,
              });
              return tableList;
            }}
            tableColumns={[
              {
                title: columnName,
                dataIndex: 'Name',
                key: 'TableKey',
                name: 'Name',
                width: 530,
              },
            ]}
            defaultTreeSelectKey={treeData && treeData[0]?.key}
            selectKey={selectGroup.map && selectGroup.map((item) => item.TableKey)}
            selectInfo={selectGroup}
            setSelectGroup={$selectGroup}
            selectGroup={selectGroup}
            getTableList={getTableList}
            paginationChange={() => { }}
            showTagList={showTag}
          />
        </Modal>
      )}
    </>
  );
};

/** 打开消息分组选择的方法 */
export const openSelectMessageGroup: (params?: {
  defaultValue?: {
    Id: string;
    TableKey: string;
    Name: string;
    AppId: string;
  }[] | null;
}) => Promise<string> = (params: any) => {
  return new Promise((resolve, reject) => {
    const unmount = RenderModalToBody(
      createElement(SelectMessageGroup, {
        value: Array.isArray(params.defaultValue) ? params.defaultValue : [],
        hideSelectVisible: true,
        onChange: (val: string) => {
          unmount()
          resolve(val)
        },
        onCancel: () => {
          unmount()
          reject()
        },
      }),
    );
  })
}

export default SelectMessageGroup;

const DragHandle = SortableHandle(() => (
  <>
    <svg
      xmlns="http://www.w3.org/2000/svg"
      width="12"
      height="12"
      viewBox="0 0 12 12"
    >
      <g id="拖动排序" transform="translate(-5273 -5499)">
        <g id="组_5531" data-name="组 5531" transform="translate(4593 5321)">
          <circle
            id="椭圆_178"
            data-name="椭圆 178"
            cx="1"
            cy="1"
            r="1"
            transform="translate(682 178)"
            fill="#ccc"
          />
          <circle
            id="椭圆_179"
            data-name="椭圆 179"
            cx="1"
            cy="1"
            r="1"
            transform="translate(688 178)"
            fill="#ccc"
          />
          <circle
            id="椭圆_180"
            data-name="椭圆 180"
            cx="1"
            cy="1"
            r="1"
            transform="translate(682 183)"
            fill="#ccc"
          />
          <circle
            id="椭圆_181"
            data-name="椭圆 181"
            cx="1"
            cy="1"
            r="1"
            transform="translate(688 183)"
            fill="#ccc"
          />
          <circle
            id="椭圆_182"
            data-name="椭圆 182"
            cx="1"
            cy="1"
            r="1"
            transform="translate(682 188)"
            fill="#ccc"
          />
          <circle
            id="椭圆_183"
            data-name="椭圆 183"
            cx="1"
            cy="1"
            r="1"
            transform="translate(688 188)"
            fill="#ccc"
          />
        </g>
      </g>
    </svg>
  </>
));

const SortableItem = SortableElement(
  ({ item, del }: { item: any; del: (id: string) => void }) => (
    <div className={nowStyle['message-list-sort-item']}>
      <p><TextWidget>{item.Name}</TextWidget></p>
      <div>
        <InbizIcon type="icon-ic-delete" onClick={() => del(item.TableKey)} />
        <DragHandle />
      </div>
    </div>
  ),
);

const SortableList = SortableContainer(
  ({ sureGroup, del }: { sureGroup: any[]; del: (id: string) => void }) => {
    return (
      <div className={nowStyle.list}>
        {sureGroup.map &&
          sureGroup.map((item: any, idx: number) => {
            return (
              <SortableItem item={item} key={item.Id} index={idx} del={del} />
            );
          })}
      </div>
    );
  },
);
